<?php

/**
 * @version    $Id: crypt.class.php 1 2016-08-11 02:39:42Z tic $
 */

if(!defined('IN_SYS')) exit('Access Denied');

class crypt{

    public static function encode($string, $key, $expiry=0)
    {
        return crypt::crypt_handle($string, $key, $expiry, 'ENCODE');
    }

    public static function decode($string, $key)
    {

        return crypt::crypt_handle($string, $key, 0, 'DECODE');
    }

    private static function crypt_handle($string, $key, $expiry=0, $operation='DECODE'){
        $runtokey = $operation == 'ENCODE' ? substr(md5(microtime(true)), -4) : substr($string, 0, 4);
        $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$key), 0, 6) . $string : base64_decode(substr($string, 4));
        
        $keys = md5($runtokey.$key);
        $string_len = strlen($string);
        while(strlen($keys)<$string_len){
            $keys .= md5($runtokey.$key.strlen($keys));
        }

        $result = '';
        $string_length = strlen($string);
        for ($i = 0; $i < $string_length; $i++) {
            $result .= $string{$i} ^ $keys{$i};
        }
        if ($operation == 'ENCODE') {
            return $runtokey . str_replace('=', '', base64_encode($result));
        } else {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 6) == substr(md5(substr($result, 16).$key), 0, 6)) {
                return substr($result, 16);
            } else {
                return '';
            }
        }
    }

	public static function  to62($num) {
		$dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$ret = '';
		do {
			$ret = $dict[bcmod($num, 62)] . $ret;
			$num = bcdiv($num, 62);
		} while ($num > 0);
		return $ret;
	}

	public static function  from62($num) {
		$num = strval($num);
		$dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$len = strlen($num);
		$dec = 0;
		for($i = 0; $i < $len; $i++) {
			$pos = strpos($dict, $num[$i]);
			$dec = bcadd(bcmul(bcpow(62, $len - $i - 1), $pos), $dec);
		}
		return $dec;
	}

}

?>